package com.leapp.sk.wxapi

import android.os.Bundle
import com.example.mvp.activity.BaseActivityMVP
import com.example.mvp.binder.BaseDataBinder
import com.leapp.sk.binder.login.WXEntryLoginBinder
import com.leapp.sk.viewdelegate.login.WXEntryLoginDelegate
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import android.content.Intent
import android.text.TextUtils
import cc.vv.lkbasecomponent.http.LKHttp
import cc.vv.lkbasecomponent.http.lib.CallBack
import cc.vv.lkbasecomponent.http.lib.setting.Settings
import cc.vv.lklibrary.http.base.okhttpfactory.plugins.httpplugin.MediaTypeWrap
import com.example.baselibrary.util.LKToastUtil
import com.leapp.sk.util.wxentry.WXLoginUtil
import com.tencent.mm.opensdk.openapi.IWXAPI
import cc.vv.lklibrary.log.LogOperate
import com.example.util.APP_ID_WX
import com.example.util.APP_SECRET_WX
import com.example.util.ObjectProcessingUtil
import com.leapp.sk.R
import com.leapp.sk.app.CHECK_OPENID
import com.leapp.sk.bean.*
import com.leapp.sk.bean.request.login.AccessTokenRequestEntity
import com.leapp.sk.bean.request.login.WXUserInfoRequestEntity
import com.leapp.sk.bean.response.login.LoginResponseEntity
import com.leapp.sk.sever.login.UserInfoSever
import com.leapp.sk.ui.activity.AppMainTableActivity
import com.leapp.sk.ui.activity.join.SearchClassActivity
import com.leapp.sk.ui.activity.join.ToExamineActivity
import com.leapp.sk.ui.activity.login.LoginMobileVerificationActivity
import com.leapp.sk.ui.activity.login.PerfectUserInfoActivity
import com.example.util.finallist.SKCODE_200
import com.example.util.finallist.SKCODE_901
import com.example.util.finallist.WX_USER_INFO
import com.tencent.mm.opensdk.modelmsg.SendAuth




/**
 * 微信登录为空白页面
 * @author  chaohaipeng  on 2018/7/9.
 */
class WXEntryActivity : BaseActivityMVP<WXEntryLoginDelegate>(), IWXAPIEventHandler {

    /**
     * 微信登录相关
     */
    var api: IWXAPI? = null

    override fun onResp(baseResp: BaseResp?) {
        when (baseResp?.errCode) {
            BaseResp.ErrCode.ERR_OK->{
                getAccesToken(baseResp)
            }
            BaseResp.ErrCode.ERR_USER_CANCEL -> showMsg(2)
            BaseResp.ErrCode.ERR_AUTH_DENIED -> showMsg(3)

        }


    }

    override fun onReq(p0: BaseReq?) {
        LogOperate.e("微信分析==="+p0.toString())
    }

    override fun initDate() {
        api = WXLoginUtil.initWXEntryLogin(this)
        WXLoginUtil.checkIntent(this,api)
    }

    override fun bindEvenListener() {
    }

    override fun getDelegateClass(): Class<WXEntryLoginDelegate> {
        return WXEntryLoginDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {
        return WXEntryLoginBinder()
    }

    override fun initView(p0: Bundle?) {
        notifyModelChanged("1")
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
        super.onActivityResult(requestCode, resultCode, data)
        api?.handleIntent(data, this)
    }

    /**
     * 登录回调消息
     */
    fun showMsg(code: Int) {
        when (code) {
            1 -> LKToastUtil.showToastLong("发送成功")
            2 -> LKToastUtil.showToastLong("发送取消")
            3 -> LKToastUtil.showToastLong("发送被拒绝")
            else -> ""

        }
        finish()

    }
    /**
     * 判断是否绑定手机号
     * @param accessTokenEntity
     */
    private fun getcheckOpenid( objWXUserInfo: WXUserInfo?) {
        if (objWXUserInfo==null){
            return
        }
        val mutableMapOf = mutableMapOf<String, String>()
        mutableMapOf.put("openid",objWXUserInfo.openid)
        LKHttp.post(CHECK_OPENID,mutableMapOf,LoginResponseEntity::class.java, object: CallBack<LoginResponseEntity>(){
            override fun onSuccess(url: String?, obj: LoginResponseEntity?) {
                super.onSuccess(url, obj)
                if (obj?.code == SKCODE_200) {
                    UserInfoSever.getInstance().saveData(obj)
                    val userInfoEntity: UserInfoEntity = ObjectProcessingUtil.objMandatoryConversionClass(obj?.data, UserInfoEntity::class.java)
                    val name=userInfoEntity?.name
                    if (userInfoEntity.status==0){
                        if (TextUtils.isEmpty(name)){
                            val intent: Intent = Intent(this@WXEntryActivity, PerfectUserInfoActivity::class.java)
                            startActivity(intent)
                        }else{
                            val intent: Intent = Intent(this@WXEntryActivity, SearchClassActivity::class.java)
                            startActivity(intent)
                        }
                    }else if (userInfoEntity.status==1){
                        val intent: Intent = Intent(this@WXEntryActivity, AppMainTableActivity::class.java)
                        startActivity(intent)
                    }else{
                        val intent: Intent = Intent(this@WXEntryActivity, ToExamineActivity::class.java)
                        startActivity(intent)
                    }
                }else if (obj?.code == SKCODE_901){
                    val intent: Intent = Intent(this@WXEntryActivity, LoginMobileVerificationActivity::class.java)
                    intent.putExtra(WX_USER_INFO,objWXUserInfo)
                    startActivity(intent)
                }

            }

            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
            }

        } ,true,Settings(MediaTypeWrap.MEDIA_TYPE_FORM))

    }


    /**
     * 获取token
     */
    private fun getAccesToken(baseResp: BaseResp?) {
        val url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"
        val code = (baseResp as SendAuth.Resp).code
        LogOperate.e("响应======="+baseResp)
        val baseRequestEntity = AccessTokenRequestEntity()
        baseRequestEntity.appid=APP_ID_WX
        baseRequestEntity.secret=APP_SECRET_WX
        baseRequestEntity.code=code
        LKHttp.post(url, baseRequestEntity, WXAccessTokenEntity::class.java, object : BaseCallBack<WXAccessTokenEntity>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: WXAccessTokenEntity?) {
                super.onSuccess(url, resultText, obj)
                LogOperate.e("微信获取token==="+obj.toString())
                if (obj!=null){
                    getUserInfo(obj)
                }


            }
            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))

    }

    /**
     * 获取个人信息
     */
    private fun getUserInfo(accessTokenEntity:WXAccessTokenEntity) {
        val url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID"
        val baseRequestEntity = WXUserInfoRequestEntity()
        baseRequestEntity.access_token=accessTokenEntity.access_token
        baseRequestEntity.openid=accessTokenEntity.openid
        LKHttp.post(url, baseRequestEntity, WXUserInfo::class.java, object : BaseCallBack<WXUserInfo>(this) {
            override fun onSuccess(url: String?, resultText: String?, obj: WXUserInfo?) {
                super.onSuccess(url, resultText, obj)
                LogOperate.e("微信获取信息==="+obj.toString())
                getcheckOpenid(obj)
            }
            override fun onFailure(url: String?, isLoading: Boolean, exceptionStr: String?) {
                super.onFailure(url, isLoading, exceptionStr)
                LKToastUtil.showToastShort(resources.getString(R.string.app_net_erro))
            }
        }
                , true, Settings(MediaTypeWrap.MEDIA_TYPE_FORM))

    }

}